const util = require('util');
const debug = util.debuglog('oil-game:upgrade:cron');
const dispatcher = require('../../../util/dispatcher');

module.exports = function (app) {
    return new Handler(app);
};
let Handler = function (app) {
    this.app = app;
};
let handler = Handler.prototype;

const {
    doubleRewardExists, //判断双倍奖励是否开启
} = require('../lib/cache');

//每5秒向客户端推送增加的金币
handler.showGold = async function () {
    try {
        //当前所有在线的用户
        let users = await getAllUsers.call(this);
        if (users.length < 1) return;
        //通知所有用户当前的金币数量
        for (let i = 0; i < users.length; i++) {
            pushMsgUserCoins.call(this, users[i]);
        }
    } catch (err) {
        debug("向客户端发送用户的当前金币数量发生异常 %s", JSON.stringify(err));
        return [];
    }
};

//汇总全部的Channel在线用户
async function getAllUsers() {
    let self = this;
    let connectorServers = this.app.getServersByType('connector');
    let loginServers = this.app.getServersByType('login');
    let upgradeServers = this.app.getServersByType('upgrade');
    if (!(loginServers && loginServers.length > 0)) return [];

    let users = [];
    for (let i = 0; i < loginServers.length; i++) {
        let item = loginServers[i];
        let itemUsers = await getChannelAllUsers.call(this, item.id);
        for (let key in itemUsers) {    //获取所有的用户
            let {uid, last_login_time, last_logout_time, levelInfo} = itemUsers[key];
            if (last_login_time < last_logout_time) break;   //用户离线
            let server_id = item.id;
            let frontend_id = dispatcher.dispatch(uid, connectorServers).id;
            let upgrade_id = dispatcher.dispatch(uid, upgradeServers).id;
            let login_id = dispatcher.dispatch(uid, loginServers).id;
            if (levelInfo && levelInfo.length > 0) {
                let product = await getProductCoins.call(this, levelInfo);
                //5秒产量
                product *= 5;
                //判断是否双倍奖励
                let double = await doubleRewardExists.call(self, uid);
                if (double) {
                    product *= 2;
                }
                if (upgrade_id == this.app.serverId) {   //每个服务器都会有crons，所以此处将用户按照服务器分类返回，防止冲突
                    users.push({
                        uid,
                        server_id,
                        frontend_id,
                        upgrade_id,
                        last_login_time,
                        last_logout_time,
                        product,
                        login_id
                    });
                }
            }
        }
    }
    return users;
}

function getProductCoins(levelInfo) {
    let coins = 0;
    for (let i = 0; i < levelInfo.length; i++) {
        coins += parseInt(levelInfo[i]['product']);
    }
    return coins;
}

//获取特定Channel中所有当前在线用户
function getChannelAllUsers(sid) {
    return new Promise((resolve, reject) => {
        this.app.rpcInvoke(sid, {
            namespace: 'user',
            serverType: 'login',
            service: 'loginRemote',
            method: 'getAllUsers',
            args: [{}]
        }, function (err, result) {
            if (err) {
                debug("获取特定Channel中所有当前在线用户异常  %s", JSON.stringify(err));
                return reject(err);
            }
            resolve(result);
        });
    });
}

//通知客户端当前的金币数量
function pushMsgUserCoins(user) {
    this.app.rpcInvoke(user.upgrade_id, {
        namespace: 'user',
        serverType: 'upgrade',
        service: 'upgradeRemote',
        method: 'productCoins',
        args: [
            user.uid,
            user.frontend_id,
            user.product,
            user.login_id
        ]
    }, function () {
    });
}
